package com.web;

import com.alibaba.fastjson.JSON;
import com.proj.User;
import com.service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //收
        BufferedReader br = req.getReader();
        Map msg = JSON.parseObject(br.readLine());
        //验
        User user=new UserService().login(msg.get("account").toString(),msg.get("password").toString());
        //发
        resp.setContentType("text/json;charset=utf-8");
        Data data=new Data();
        if(user!=null){//密码正确
            //将登陆成功后的user对象，存储到session
            HttpSession session = req.getSession();
            session.setAttribute("user",user);
            //页面跳转
            data.content = req.getContextPath()+"/index.html";
            data.dataType="url_index";
            resp.getWriter().write(JSON.toJSONString(data));
        }else {//密码错误
            data.content = "账号或密码错误";
            data.dataType="message_err";
            resp.getWriter().write(JSON.toJSONString(data));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
